﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Line : MonoBehaviour
{
    public LineRenderer lineRenderer;

    public Vector3 pos1;
    public Vector3 pos2;
    public Vector3 pos1Temp;
    public Vector3 pos2Temp;

    public float distance;
    public Vector3 direction;
    public float speed = 1f;

    public int state = 0; //0静止 1伸长 2缩短

    VoidDelegate callback = null;
    void Awake()
    {
        Debug.Log("Awake");
        lineRenderer = gameObject.GetComponent<LineRenderer>();
        pos2Temp = Vector3.zero;
        state = 0;
    }

    void Update()
    {
        Move();
    }

    public void Shoot(Vector3 _pos1, Vector3 _pos2, VoidDelegate _callback = null)
    {
        state = 1;

        pos1 = _pos1;
        pos2 = _pos2;
        callback = _callback;

        direction = (pos2 - pos1).normalized;
        pos1Temp = pos1;
        pos2Temp = pos1;

        lineRenderer.positionCount = 2;
        lineRenderer.startWidth = 0.04f;
        lineRenderer.endWidth = 0.04f;
        lineRenderer.sortingOrder = 100;

        Move();
    }

    public void Move()
    {
        if (state <= 0)//0静止
        {
            return;
        }

        if (state == 1) //1伸长
        {
            pos2Temp = pos2Temp + direction * Time.deltaTime * speed;
            if ((pos2 - pos2Temp).normalized != direction)
            {
                pos2Temp = pos2;
                state++;
            }
        }
        else if (state == 2) //2缩短
        {
            pos1Temp = pos1Temp + direction * Time.deltaTime * speed;
            if ((pos2 - pos1Temp).normalized != direction)
            {
                pos1Temp = pos2;
                state++;
                if (state > 2)
                {
                    state = 0;
                    Destroy(gameObject);
                    if (callback != null)
                    {
                        callback();
                    }
                }
            }
        }
        
       
        
        lineRenderer.SetPosition(0, pos1Temp);
        lineRenderer.SetPosition(1, pos2Temp);

    }
}
